<%--
  Created by IntelliJ IDEA.
  User: Fmc
  Date: 2022/5/30
  Time: 11:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>用户展示</title>
      <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
      <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
  </head>
  <body>

    <!-- 搜索框 -->
    <form class="layui-form" action="" id="searchForm">
      <div class="layui-inline">
        <label class="layui-form-label">用户编号</label>
        <div class="layui-input-inline">
          <input type="text" id="userId" name="userId"  placeholder="请输入用户编号" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" id="userName" name="userName"  placeholder="请输入用户名" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline">
          <button class="layui-btn" lay-submit lay-filter="formDemo" id="reserch">查询</button>
          <button type="reset" class="layui-btn layui-btn-primary" id="search_reset">重置</button>
        </div>
      </div>
    </form>

    <!-- 头部工具栏 -->
    <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn layui-btn" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-danger layui-btn" lay-event="delete">删除</button>
      </div>
    </script>

    <!-- 行内工具栏 -->
    <script type="text/html" id="barDemo">
      <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="resetPwd">更改密码</a>
<%--      <a class="layui-btn layui-btn-xs" lay-event="more">更多 <i class="layui-icon layui-icon-down"></i></a>--%>
      <a class="layui-btn layui-btn-xs" lay-event="update">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>

    <!-- 添加时，弹出的表单 -->
    <form class="layui-form" action="" id="addUserForm" style="display: none">
      <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" name="userName" required lay-verify="required" placeholder="请输入用户名" class="layui-input" >
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
          <input type="text" name="password" required lay-verify="required" placeholder="请输入密码" class="layui-input">
        </div>
      </div>
      <div class="layui-inline"> <label class="layui-form-label">邮箱</label>
            <div class="layui-input-inline">
                <input type="text" name="email" lay-verify="email" autocomplete="off" placeholder="请输入邮箱"class="layui-input">
            </div>
      </div>


<%--      <div class="layui-form-item">--%>
<%--        <label class="layui-form-label">部门名称</label>--%>
<%--        <div class="layui-input-inline">--%>
<%--&lt;%&ndash;          <input type="text" name="deptid" required lay-verify="required" placeholder="请输入部门编号" class="layui-input">&ndash;%&gt;--%>
<%--          <select name="deptid" lay-verify="" id="deptMenuAdd">--%>

<%--          </select>--%>
<%--        </div>--%>
<%--      </div>--%>


        <div class="layui-form-item">
            <label class="layui-form-label">头像</label>
            <input type="hidden" name="avatar" id="avatar">
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="demo1" style="width: 100px;height: 80px">
                <SPAN id="demoText" style="color: red"></SPAN>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <%--进度条--%>
                <div style="width: 95px;">
                    <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                        <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                </div>
                <button type="button" class="layui-btn" id="test1">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>

        <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="addUser">提交</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>
    <!-- 修改时，弹出的表单 -->
    <form class="layui-form" action="" lay-filter="updateUserFilter" id="updateUserForm" style="display: none">
      <div class="layui-form-item">
        <label class="layui-form-label">用户编号</label>
        <div class="layui-input-inline">
          <input type="text" name="userId" disabled required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" name="userName" required lay-verify="required"  class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
          <input type="text" name="password"  required lay-verify="required"  class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">盐值</label>
        <div class="layui-input-inline">
          <input type="text" name="salt"  required lay-verify="required"  class="layui-input">
        </div>
      </div>
<%--      <div class="layui-form-item">--%>
<%--        <label class="layui-form-label">部门名称</label>--%>
<%--        <div class="layui-input-inline">--%>
<%--&lt;%&ndash;          <input type="text" name="deptid" required lay-verify="required"  class="layui-input">&ndash;%&gt;--%>
<%--          <select name="deptid" lay-verify="" id="deptMenuUpdate">--%>

<%--          </select>--%>
<%--        </div>--%>
<%--      </div>--%>

        <!--修改头像-->
        <div class="layui-form-item">
            <label class="layui-form-label">头像</label>
            <input type="hidden" name="avatar" id="avatarUp">
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="demo2" style="width: 100px;height: 80px">
                <span id="demoText1" style="color: red"></span>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <%--进度条--%>
                <div style="width: 95px;">
                    <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                        <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                </div>
                <button type="button" class="layui-btn" id="test2">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
            </div>
        </div>



        <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="updateUser">保存</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>

    <!-- 重置密码时，弹出的表单 -->
    <form class="layui-form" action="" lay-filter="resetPwdFilter" id="resetPwdForm" style="display: none">
        <div class="layui-form-item">
            <label class="layui-form-label">用户编号</label>
            <div class="layui-input-inline">
                <input type="text" name="userId" disabled required lay-verify="required" readonly class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">新密码</label>
            <div class="layui-input-inline">
                <input type="text" name="password" required lay-verify="required" placeholder="请输入新密码"  class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="resetPwdBtn">保存</button>
            </div>
        </div>
    </form>

    <!-- table表格 -->
    <%--lay-filter相当于dom元素的id，layui专用的选择器--%>
    <table id="demo" lay-filter="test"></table>

  </body>
  <script>

      layui.use(['table', 'form', 'jquery', 'upload', 'element', 'layer'], function () {
          var table = layui.table,
              form = layui.form,
              $ = layui.jquery
              ,upload = layui.upload
              ,element = layui.element
              ,layer = layui.layer;

      //第一个实例,渲染数据
      table.render({
        elem: '#demo'
        ,height: 500
        ,url: '${pageContext.request.contextPath}/user/findAllUser.do'//数据接口
        ,page: true//开启分页
        ,limit: 5
        ,limits:[5,10,15,20,25,30]
        ,autoSort: false//禁用前端的自动排序，开启后端的服务器排序
        ,toolbar: '#toolbarDemo'
        ,cols: [[
          //表头
          {type: 'checkbox', fixed: 'left'}
          ,{field: 'userId', title: '用户编号', width:110, sort: true, fixed: 'left'}
          // ,{field: 'deptId', title: '部门id', width:80}
          // ,{field: 'loginName', title: '登录名', width:80}
          ,{field: 'userName', title: '用户名', width:80}
          ,{field: 'email', title: '邮箱', width:60}
          // ,{field: 'phoneNumber', title: '电话号码', width: 110,}
           ,{field:'avatar',  title: '头像', width: 150
                  ,templet: function(d){
                      console.log(d.LAY_INDEX); //得到序号。一般不常用
                      console.log(d.LAY_COL); //得到当前列表头配置信息（layui 2.6.8 新增）。一般不常用
                      console.log(d.avatar)
                      //得到当前行数据，并拼接成自定义模板
                      return '<img onclick="showimg(this)" style="display: inline-block; width: 50%; height: 100%;" src="'+d.avatar+'" >'
                  }
           }
           ,{field: 'password', title: '密码', width: 120,}
           ,{field: 'salt', title: '盐值', width: 120,}
           // ,{field: 'status', title: '状态', width: 60,}
           // ,{field: 'delFlag', title: '删除日志', width: 110,}
           // ,{field: 'createBy', title: '创建人', width: 90,}
           ,{field: 'createTime', title: '创建时间', width: 120,}
           // ,{field: 'updateBy', title: '修改人', width: 90,}
           ,{field: 'updateTime', title: '修改时间', width: 120,}
           ,{field: 'remark', title: '注释', width: 60,}
          ,{fixed: 'right', title: '操作', width: 200, align:'center', toolbar: '#barDemo'}
        ]]
      });

      //触发排序事件
      table.on('sort(test)', function(obj){ //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值 "
        console.log(obj.field); //当前排序的字段名
        console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
        console.log(this); //当前排序的 th 对象

        //尽管我们的 table 自带排序功能，但并没有请求服务端。
        //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
        table.reload('demo', {
          initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
          ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
            field: obj.field //排序字段
            ,order: obj.type //排序方式
          }
        });
      });

      //模糊查询,监听提交
      form.on('submit(formDemo)', function(data){
        table.reload('demo',{
          where: {
              userId: data.field.userId
            ,userName: data.field.userName
          }
          ,page: {
            curr: 1
          }
        });
        return false;
      });

      //重置按钮绑定单击事件
      $("#search_reset").click(function(){
        table.reload('demo',{
          where: {
              userId: ""
            ,userName: ""
          },
          page: {
            curr: 1
          }
        });
      });

      //监听头部工具栏事件
      table.on('toolbar(test)', function (obj){
        //获取选中的数据
        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        console.log(data);
        switch (obj.event) {
          case 'add':
            layer.open({
              title: '添加用户'
              ,type: 1
              ,content:$('#addUserForm')
              ,area: ['500px','500px']
            });
            // 动态获取部门信息，并追加到下拉列表
            <%--  $.ajax({--%>
            <%--      url:"${pageContext.request.contextPath}/user/deptEntity.do",--%>
            <%--      type:"POST",--%>
            <%--      dataType:"JSON",--%>
            <%--      success:function (ret) {--%>
            <%--          if(ret.code==0){--%>
            <%--              //<option value="0">写作</option>--%>
            <%--              var htmlStr="";--%>
            <%--              for (let i = 0; i < ret.data.length; i++) {--%>
            <%--                  htmlStr+="<option value="+ret.data[i].deptid+">"+ret.data[i].deptname+"</option>"--%>
            <%--              }--%>
            <%--              $("#deptMenuAdd").html(htmlStr);--%>
            <%--              //重新渲染表单--%>
            <%--              layui.use('form',function () {--%>
            <%--                  var form=  layui.form;--%>
            <%--                  form.render('select');--%>
            <%--              })--%>
            <%--          }--%>
            <%--      }--%>
            <%--  });--%>
            // 监听addUserForm表单的提交事件
            form.on('submit(addUser)',function (data){
              $.ajax({
                url: '${pageContext.request.contextPath}/user/addUsers.do'
                ,data: data.field
                ,dataType: "json"
                ,type: "POST"
                ,success: function (redata) {
                  if (redata.code == 0) {
                    layer.msg(redata.msg);
                    layer.closeAll();//关闭对话框
                    table.reload('demo',{
                      page: {
                        curr: 1
                      }
                    });
                  } else {
                    layer.msg(redata.msg);
                  }
                }
              });
              return false;
            });
            break;

            case  'delete':
                if (data.length === 0) {
                    layer.msg('请选择一行');
                } else {
                    //layer.msg('删除');
                    //定义一个数组，封装所有选中的id
                    var ids = [];
                    //循环所有选中的行
                    for (let i=0;i<data.length;i++) {
                        ids[i] = data[i].userId;
                    }
                    layer.confirm('真的删除选中行吗？',function (index){
                        $.ajax({
                            url: '${pageContext.request.contextPath}/user/deleteUser.do'
                            ,data: {userId:ids.join(",")}
                            ,dataType: "json"
                            ,type: "post"
                            ,success: function (redata) {
                                if (redata.code == 0) {
                                    //关闭对话框
                                    layer.closeAll();
                                    //刷新表格数据
                                    table.reload('demo',{
                                        page: {
                                            curr: 1
                                        }
                                    });
                                }
                                layer.msg(redata.msg);
                            }
                        });
                    });
                }
                break;
        }
      });
          // layui.use(['layedit', 'laydate'], function() {
          //     var layer = layui.layer
          //         , laydate = layui.laydate;
          //     laydate.render({
          //         elem: '#createTime',
          //         type:'date',
          //         format:'yyyy-MM-dd',
          //         // value: new Date(),
          //     });
          //     laydate.render({
          //         elem: '#updateTime',
          //         // value: new Date(),
          //     });
          // })

        //执行实例 上传图片
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            , type: "post"
            , url: '${pageContext.request.contextPath}/user/imgUpload.do' //上传接口
            , accept: 'images'//只允许上传图片
            , acceptMime: 'image/*'//只显示图片文件
            /*,auto: false//禁用自动上传
            ,bindAction: '#addSub'*/
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
                element.progress('demo', '0%'); //进度条复位
                layer.msg('上传中', {icon: 16, time: 0});
            }
            , done: function (res) {
                console.log(res)
                //如果上传失败
                if (res.code == 0) {
                    let src = res.data.src;
                    console.log(src)
                    $("#avatar").val(src);
                    $("#demoText").html(res.msg)
                    /*$('#demo1').attr('src', src);*/
                } else {
                    $("#demoText").html(res.msg)
                    return layer.msg('上传失败');
                }
                //上传完毕回调
            }
            , error: function () {
                //请求异常回调
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                if (n == 100) {
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });
            //监听行工具事件
        // 下拉菜单
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var userId = data.userId;
            console.log(userId);
            if(layEvent === 'resetPwd'){
                // 重置密码
                layer.open({
                    title: '重置密码'
                    ,type: 1
                    ,content: $('#resetPwdForm')
                    ,area: ["500px","500px"]
                });
                form.val('resetPwdFilter',{
                    "userId": data.userId
                    ,"password": data.password
                    ,"salt": data.salt
                });
                // 提交表单
                form.on('submit(resetPwdBtn)',function (data) {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/user/updatePwd.do"
                        ,data: data.field
                        ,dataType: "json"
                        ,type: "post"
                        ,success: function (redata) {
                            if (redata.code == 0) {
                                layer.closeAll();//关闭对话框
                                layer.msg(redata.msg);
                                table.reload('demo',{
                                    page: {
                                        curr: 1
                                    }
                                });
                                window.location.href = "../login.jsp";
                            } else {
                                layer.msg(redata.msg);
                            }
                        }
                    });
                    return false;
                });
            } else if (layEvent === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    //删除数据库中
                    $.ajax({
                        url: "${pageContext.request.contextPath}/user/deleteUser.do",
                        type: "POST",
                        dataType: "JSON",
                        data: {userId: data.userId},
                        success: function (data) {
                            if (data.code == 0) {
                                //关闭对话框
                                layer.closeAll(); //疯狂模式，关闭所有层
                                //刷新表格数据
                                table.reload('demo');
                            }
                            layer.msg(data.msg);
                        }
                    });
                });
            } else if (layEvent === 'update') {
                layer.open({
                    title: '修改用户信息'
                    ,type: 1
                    ,content: $('#updateUserForm')
                    ,area: ["500px","500px"]
                });
                // 回显用户信息
                form.val('updateUserFilter',{
                    "userId": data.userId
                    ,"userName": data.userName
                    ,"password": data.password
                    ,"salt": data.salt
                    ,"avatar":$("#demo2").attr("src",data.avatar)
                });
                // 动态的获取部门表信息
                <%--$.ajax({--%>
                <%--    url:"${pageContext.request.contextPath}/user/deptEntity.do",--%>
                <%--    type:"POST",--%>
                <%--    dataType:"JSON",--%>
                <%--    success:function (ret) {--%>
                <%--        if(ret.code==0){--%>
                <%--            //<option value="0">写作</option>--%>
                <%--            var htmlStr="";--%>
                <%--            for (let i = 0; i < ret.data.length; i++) {--%>
                <%--                htmlStr+="<option value="+ret.data[i].deptid+">"+ret.data[i].deptname+"</option>"--%>
                <%--            }--%>
                <%--            $("#deptMenuUpdate").html(htmlStr);--%>
                <%--            //重新渲染表单--%>
                <%--            layui.use('form',function () {--%>
                <%--                var form=  layui.form;--%>
                <%--                form.render('select');--%>
                <%--            })--%>
                <%--        }--%>
                <%--    }--%>
                <%--});--%>
                // 更新用户信息
                form.on('submit(updateUser)',function (data) {
                    $.ajax({
                        url: "${pageContext.request.contextPath}/user/updateUser.do"
                        ,data: data.field  //,_method:"put"
                        ,dataType: "json"
                        ,type: "post"
                        ,success: function (redata) {
                            if (redata.code == 0) {
                                layer.closeAll();//关闭对话框
                                table.reload('demo',{
                                    page: {
                                        curr: 1
                                    }
                                });
                                <%--window.location.href = "${pageContext.request.contextPath}/login.jsp"--%>
                            } else {
                                layer.msg(redata.msg);
                            }
                        }
                    });
                    return false;
                });
            }
        });
          var uploadInst = upload.render({
              elem: '#test2' //绑定元素
              , type: "post"
              , url: '${pageContext.request.contextPath}/user/imgUpload.do' //上传接口
              , accept: 'images'//只允许上传图片
              , acceptMime: 'image/*'//只显示图片文件
              /*,auto: false//禁用自动上传
              ,bindAction: '#addSub'*/
              , before: function (obj) {
                  //预读本地文件示例，不支持ie8
                  obj.preview(function (index, file, result) {
                      $('#demo2').attr('src', result); //图片链接（base64）
                  });
                  element.progress('demo', '0%'); //进度条复位
                  layer.msg('上传中', {icon: 16, time: 0});
              }
              , done: function (res) {
                  console.log(res)
                  //如果上传失败
                  if (res.code == 0) {
                      let src = res.data.src;
                      $("#avatarUp").val(src);
                      $("#demoText1").html(res.msg)
                      /*$('#demo2').attr('src', src);*/
                  } else {
                      return layer.msg('上传失败');
                  }
                  //上传完毕回调
              }, error: function () {
                  //请求异常回调
                  //演示失败状态，并实现重传
                  var demoText = $('#demoText');
                  demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                  demoText.find('.demo-reload').on('click', function () {
                      uploadInst.upload();
                  });
              }
              //进度条
              , progress: function (n, elem, e) {
                  element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                  if (n == 100) {
                      layer.msg('上传完毕', {icon: 1});
                  }
              }
          });
    });
  </script>
</html>

